<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise发送AJAX</title>
</head>
    <button>AJAX</button>

    <script>
        //获取按钮
        let btn = document.querySelector('button');

        //绑定事件
        btn.onclick = function(){
            let p = new Promise((resolve, reject) => {
                //
                let xhr = new XMLHttpRequest();
                //
                xhr.open('get', 'http://api.xiaohigh.com/duanzi');
                //
                xhr.send();
                //
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        //成功  响应状态码  1xx  2xx  3xx  4xx 5xx
                        if(xhr.status >= 200 && xhr.status < 300){
                            //输出响应体结果
                            resolve(xhr.response);
                        }else{
                            //失败
                            reject(xhr.status);
                        }
                    }
                }
            })
        
            //调用 then 方法处理结果    形参的名字可以任意编写
            p.then(v => {
                console.log(v);
            }, r => {
                console.error(r);// error 是 console 方法, 是红色的警告输出
            })
        }

    </script>
<body>
</body>
</html>